<template>
	<view class="application-form">
		<view class="card">
			<!-- <view class="margin-b32">
				<text class="font-size-34">{{ company.title }}</text>
				<text class="font-size-26 text-muted">（{{company.msg}}）</text>
			</view> -->
			<form>
				<view class="form-item">
					<view class="lable">
						<text>用车事由</text><text v-if="false" class="text-red">*</text>
					</view>
					<view class="form-body">
						<textarea cols="30" rows="10" v-model="formData.car_reasons" placeholder="请输入用车事由"></textarea>
					</view>
				</view>
				<view class="form-item">
					<view class="lable">
						<text>申请人</text><text class="text-red">*</text>
					</view>
					<view class="form-body">
						<input type="text" v-model="formData.applicant_name" placeholder="请输入申请人姓名">
					</view>
				</view>
				<view class="form-item">
					<view class="lable">
						<text>联系电话</text><text class="text-red">*</text>
					</view>
					<view class="form-body">
						<input type="number" :maxlength="11" v-model="formData.applicant_phone" placeholder="请输入联系电话">
					</view>
				</view>
				<view class="form-item">
					<view class="lable">
						<text>目的地</text><text v-if="false" class="text-red">*</text>
					</view>
					<view class="form-body">
						<input type="text" v-model="formData.car_destination" placeholder="请输入目的地">
					</view>
				</view>
				<view class="form-item">
					<view class="lable">
						<text>出发时间</text><text class="text-red">*</text>
					</view>
					<view class="flex align-center">
						<view class="form-body flex-1">
							<picker class="picker" mode="date" :value="formData.start_time" :start="startDate"
								:end="endDate" @change="bindDateChange($event, 'start_time')">
								<view class="picker-box" :class="{'text-grey-51': !formData.start_time}">
									{{ formData.start_time ? formData.start_time : '年、月、日' }}</view>
							</picker>
							<!-- <datetime ref="startTime" @confirm="confirm($event, 'start_time')" :value="formData.start_time ? formData.start_time : startTime" :isSecond="false">
									<text :class="{'text-grey-51': !formData.start_time}">{{ formData.start_time ? formData.start_time : '请选择出发时间' }}</text>
								</datetime> -->
						</view>
						<view class="form-body flex-1 margin-l32">
							<picker class="picker" mode="time" :value="endTimes" start="00:00" end="23:59"
								@change="bindTimeChange($event, 'time1')">
								<view class="picker-box" :class="{'text-grey-51': !times.time1}">
									{{ times.time1 ? times.time1 : '时、分' }}</view>
							</picker>
						</view>
					</view>
				</view>
				<view class="form-item">
					<view class="lable">
						<text>预计返回时间</text><text v-if="false" class="text-red">*</text>
					</view>
					<view class="flex align-center">
						<view class="form-body flex-1">
							<picker mode="date" :value="formData.end_time" :start="startDate" :end="endDate"
								@change="bindDateChange($event, 'end_time')">
								<view class="picker-box" :class="{'text-grey-51': !formData.end_time}">
									{{ formData.end_time ? formData.end_time : '年、月、日' }}</view>
							</picker>
							<!-- <datetime ref="endTime" @confirm="confirm($event, 'end_time')" :value="formData.end_time ? formData.end_time : endTime" :isSecond="false">
									<text :class="{'text-grey-51': !formData.end_time}">{{ formData.end_time ? formData.end_time : '请选择返回时间' }}</text>
								</datetime> -->
						</view>
						<view class="form-body flex-1 margin-l32">
							<picker class="picker" mode="time" :value="endTimes" start="00:00" end="23:59"
								@change="bindTimeChange($event, 'time2')">
								<view class="picker-box" :class="{'text-grey-51': !times.time2}">
									{{ times.time2 ? times.time2 : '时、分' }}</view>
							</picker>
						</view>
					</view>
				</view>
			</form>
		</view>

		<view style="height: 200rpx;"></view>
		<view class="footer" :style="{'padding-bottom': safeAreaBottom ? safeAreaBottom+'px' : '24rpx'}">
			<button :class="{'active': status}" :disabled="!status" @click="goSelCat">下一步</button>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	const checker = require("@/utils/checker.js");

	export default {
		data() {
			return {
				formData: {
					form_type: 1, // 表单类型
					car_reasons: '', // 用车事由
					applicant_name: '', // 申请人
					applicant_phone: '', // 联系电话
					car_destination: '', // 目的地
					start_time: '', // 出发时间
					end_time: '', // 还车时间
					car_data: [],
				},
				rule: [
					// { name: "car_reasons", checkType: "notnull", checkRule: "", errorMsg: "用车事由必填" },
					{
						name: "applicant_name",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "申请人必填"
					},
					{
						name: "applicant_phone",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "联系电话必填"
					},
					// { name: "car_destination", checkType: "notnull", checkRule: "", errorMsg: "目的地必填" },
					{
						name: "start_time",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "出发时间必填"
					},
					// { name: "end_time", checkType: "notnull", checkRule: "", errorMsg: "返回时间必填" },
				],
				status: false,
				orderId: '',
				endTime: '',
				startTime: '',

				times: {
					time1: '',
					time2: ''
				},
				endTimes: '00:00'
			};
		},
		computed: {
			...mapState('common', ['company', 'safeAreaBottom']),
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		watch: {
			formData: {
				deep: true,
				handler() {
					const checkRes = checker.check(this.formData, this.rule);
					if (checkRes) {
						this.status = true
					} else {
						this.status = false
					}
				}
			}
		},
		onLoad(options) {
			if (options.formData) {
				const formData = JSON.parse(decodeURIComponent(options.formData))
				this.formData = formData
			} 
			this.orderId = options.orderId
			this.endTimes = `${new Date().getHours()}:${new Date().getMinutes()}`

			if (this.orderId) {
				// this.getInfo()
			}

			uni.$on('again', () => {
				this.formData = {
					form_type: 1,
					car_reasons: '', // 用车事由
					applicant_name: '', // 申请人
					applicant_phone: '', // 联系电话
					car_destination: '', // 目的地
					start_time: '', // 出发时间
					end_time: '', // 还车时间
					car_data: [],
				}
				this.times = {
					time1: '',
					time2: ''
				}
			})
		},
		onShow() {
			// this.endTimes = `${new Date().getHours()}:${new Date().getMinutes()}`
			this.getUserInfo()
			this.formData.start_time = this.$dayjs(new Date()).format('YYYY-MM-DD')
			this.endTimes = this.$dayjs(new Date()).add(1, 'hour').format('HH:mm')
			this.times.time1 = this.$dayjs(new Date()).add(1, 'hour').format('HH:mm')
		},
		onUnload() {
			uni.$off('again')
		},
		methods: {
			getUserInfo() {
				this.$api.myUserInfoApi().then(res=> {
					this.formData.applicant_name = res.data.name
					this.formData.applicant_phone = res.data.phone
				}).catch(err=> {
					console.log('err', err);
				})
			},
			// 获取详情
			getInfo() {
				this.$api.orderDetailsApi({
					id: this.orderId
				}).then(res => {
					const start = res.data.start_time.split(' ');
					let end = []
					if (res.data.end_time) {
						end = res.data.end_time.split(' ');
					}
					const startArr = start[1].split(':')
					let endArr = []
					if (end.length) {
						endArr = end[1].split(':')
					}
					this.times = {
						time1: `${startArr[0]}:${startArr[1]}`,
						time2: endArr.length ? `${endArr[0]}:${endArr[1]}` : ''
					}
					this.formData = {
						id: this.orderId,
						form_type: res.data.form_type,
						car_reasons: res.data.car_reasons, // 用车事由
						applicant_name: res.data.applicant_name, // 申请人
						applicant_phone: res.data.applicant_phone, // 联系电话
						car_destination: res.data.car_destination, // 目的地
						start_time: start[0], // 出发时间
						end_time: end[0], // 还车时间
						car_data: this.formData.car_data,
					}
					console.log('formData', this.formData);
				}).catch(err => {
					console.log(err);
				})
			},
			// 前往选择车辆
			goSelCat() {
				const checkRes = checker.check(this.formData, this.rule);
				if (checkRes) {
					const params = JSON.parse(JSON.stringify(this.formData))
					if (this.times.time1) {
						params.start_time = `${params.start_time} ${this.times.time1}:00`
					} else {
						params.start_time = `${params.start_time} 00:00:00`
					}
					
					if (params.end_time) {
						if (this.times.time2) {
							params.end_time = `${params.end_time} ${this.times.time2}:00`
						} else {
							params.end_time = `${params.end_time} 23:59:59`
						}
					}
					
					console.log('params', params);

					const startdate = new Date(params.start_time).getTime()
					const enddate = new Date(params.end_time).getTime()
					// console.log('startdate',startdate);
					// console.log('enddate',enddate);
					// console.log('startdate',enddate > startdate);
					// if (enddate > startdate) {
					uni.navigateTo({
						url: '/pages/confirm/confirm?formData=' + encodeURIComponent(JSON.stringify(params))
						// url: '/pages/select-cat/select-cat?formData=' + encodeURIComponent(JSON.stringify(params))
					})
					// } else {
					// 	uni.showToast({
					// 		icon: 'none',
					// 		title: '返回时间不能小于出发时间'
					// 	})
					// }

				} else {
					uni.showToast({
						title: checker.error,
						icon: "none"
					});
				}

			},
			// 选择时间
			bindDateChange(event, type) {
				const {
					value
				} = event.detail
				if (type === 'start_time') {
					this.formData.start_time = `${value}`
				} else {
					this.formData.end_time = `${value}`
				}
				console.log('formData', this.formData);
			},

			bindTimeChange(event, type) {
				const {
					value
				} = event.detail
				if (type === 'time1') {
					this.times.time1 = `${value}`
				} else {
					this.times.time2 = `${value}`
				}
			},

			// 选择时间 -- 后期删除
			confirm(res, type) {
				const time = res[0] + '-' + res[1] + '-' + res[2] + ' ' + res[3] + ':' + res[4] + ':00'
				if (type === 'start_time') {
					if (this.formData.end_time) {
						let start = new Date(time).getTime()
						let end = new Date(this.formData.end_time).getTime()
						if (start < end) {
							this.formData[type] = time;
							this.endTime = res[0] + '-' + res[1] + '-' + res[2] + ' ' + (res[3] + 1) + ':' + res[4] + ':00'
							this.$refs.endTime.init()
						} else {
							uni.showToast({
								icon: 'none',
								title: '出发时间不能大于返回时间'
							})
						}
					} else {
						this.formData[type] = time;
						this.endTime = res[0] + '-' + res[1] + '-' + res[2] + ' ' + (res[3] + 1) + ':' + res[4] + ':00'
						this.$refs.endTime.init()
					}
				} else {
					if (this.formData.start_time) {
						let start = new Date(this.formData.start_time).getTime()
						let end = new Date(time).getTime()
						if (start < end) {
							this.formData[type] = time;
							this.startTime = res[0] + '-' + res[1] + '-' + res[2] + ' ' + (res[3] + 1) + ':' + res[4] +
								':00'
							this.$refs.startTime.init()
						} else {
							uni.showToast({
								icon: 'none',
								title: '返回时间不能小于出发时间'
							})
						}
					} else {
						this.formData[type] = time;
						this.startTime = res[0] + '-' + res[1] + '-' + res[2] + ' ' + (res[3] + 1) + ':' + res[4] + ':00'
						this.$refs.startTime.init()
					}
				}
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.application-form {
		padding: 32rpx;
		box-sizing: border-box;

		.form-item {
			margin-bottom: 32rpx;

			.lable {
				font-size: 28rpx;
				margin-bottom: 12rpx;
			}

			.form-body {
				display: flex;
				border-radius: 8rpx;
				border: 1rpx solid #eee;

				textarea {
					padding: 12rpx;
					height: 120rpx;
					font-size: 28rpx;
				}

				input {
					width: 100%;
					height: 72rpx;
					padding: 12rpx;
					font-size: 28rpx;
					line-height: 72rpx;
					box-sizing: border-box;
				}

				picker {
					width: 100%;
					line-height: 1;
					box-sizing: border-box;
				}

				.picker-box {
					flex: 1;
					width: 100%;
					height: 72rpx;
					display: flex;
					padding: 12rpx;
					font-size: 28rpx;
					align-items: center;
					box-sizing: border-box;
				}

				.picker {
					flex: 1;
				}
			}
		}

		.footer {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			width: 100%;
			z-index: 9;
			padding: 24rpx 32rpx;
			box-sizing: border-box;
			background-color: #FFFFFF;
			box-shadow: 0rpx 0rpx 22rpx rgba(0, 0, 0, 0.1);

			button {
				height: 84rpx;
				color: #FFFFFF;
				font-size: 32rpx;
				line-height: 84rpx;
				border-radius: 100rpx;
				background-color: rgba(0, 0, 0, 0.3);

				&::after {
					border: none;
				}
			}

			.active {
				background-color: var(--primary-color) !important;
			}
		}
	}
</style>